#include "qProdSmetkakorekcija.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlRecord>
#include "chelperclass.h"
#include <QDesktopWidget>



QProdSmetkaKorekcija::QProdSmetkaKorekcija(QWidget *parent)
	: QMyBaseFormWidget(parent)
    ,selRow(-1)
    ,textId("")
    ,komintentID("")
    ,artikal_sifra("")
    , pItemDelegate(0)
    , editorOpen(0)
{
	ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.lineEdit->setFocus();
    ui.lineEdit->setText("");
    ui.lineEdit->setStyleSheet("background-color: yellow");

    ui.lineEdit_2->setText("");
    ui.lineEdit->installEventFilter(this);
    ui.lineEdit_2->installEventFilter(this);
    ui.lineEdit_3->installEventFilter(this);
    ui.lineEdit_4->installEventFilter(this);
    ui.lineEdit_5->installEventFilter(this);
    ui.lineEdit_7->installEventFilter(this);
	ui.dateTimeEdit->installEventFilter(this);

    connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(on_pushButton1AA_clicked()));
	connect(ui.lineEdit_8, SIGNAL(returnPressed()), this, SLOT(on_pushButton1AA8_clicked()));

	connect(ui.lineEdit_2, SIGNAL(returnPressed()), this, SLOT(on_pushButton2AAA_2_clicked()));

	connect(ui.lineEdit_3, SIGNAL(returnPressed()), this, SLOT(on_plineEdit3_Pressed()));
	connect(ui.lineEdit_4, SIGNAL(returnPressed()), this, SLOT(on_plineEdit4_Pressed()));
	connect(ui.lineEdit_12, SIGNAL(returnPressed()), this, SLOT(on_plineEdit12_Pressed()));

	connect(ui.lineEdit_3, SIGNAL(editingFinished()), this, SLOT(updateModelData())); // kol
	connect(ui.lineEdit_4, SIGNAL(editingFinished()), this, SLOT(updateModelData())); // cena
	connect(ui.lineEdit_11, SIGNAL(editingFinished()), this, SLOT(updateModelData())); // rabat

    pItemDelegate = new QSTableWidgetDelegate(ui.tableView);
    connect(this ,SIGNAL(editCell()),this,SLOT(openEditor()));
    connect(this ,SIGNAL(closeCell()),this,SLOT(closeEditor()));
	connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(callImportIspratnici()));


    ui.tableView->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui.tableView->setItemDelegate(pItemDelegate);

	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));


	model = new QStandardItemModel(0, 10);
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("Шифра."));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("Назив на\nСтоките"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("Единечна\nмера"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Кол*"));
	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Един.Цена"));
	model->setHeaderData( 5, Qt::Horizontal, trUtf8("Пропишана\nстапка ДДВ"));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("Рабат"));
	model->setHeaderData( 7, Qt::Horizontal, trUtf8("Цена продажна"));
	model->setHeaderData( 8, Qt::Horizontal, trUtf8("Износ"));
	model->setHeaderData( 9, Qt::Horizontal, trUtf8("ДДВ\nво прод. вредн"));

    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
    header->show();
}

void QProdSmetkaKorekcija::pressF9()
{
	on_pushButton_4_clicked();
}


QProdSmetkaKorekcija::~QProdSmetkaKorekcija()
{

}
void QProdSmetkaKorekcija::pressEscape()
{
    if (ui.lineEdit_2->hasFocus())
    {
        ui.pushButton_4->setFocus();
        ui.pushButton_4->setChecked(true);
    }
    else
    {
        emit closeW();
    }
}
void QProdSmetkaKorekcija::on_pushButton1AA_clicked()
{
	requestfromKomintent = 1;
	CHelperClass hclass(this);
    if (!hclass.isKomintentExists(ui.lineEdit->text()))
    {
        emit scallKomintenti((QWidget*)this, ui.lineEdit->text());
    }
    else
    {
        ui.lineEdit_8->setFocus();
    }
}

void QProdSmetkaKorekcija::on_pushButton1AA8_clicked()
{
	requestfromKomintent = 2;
	CHelperClass hclass(this);
	if (!hclass.isKomintentExists(ui.lineEdit_8->text()))
	{
		emit scallKomintenti((QWidget*)this, ui.lineEdit_8->text());
	}
	else
	{
		ui.lineEdit_2->setFocus();
	}
}

void QProdSmetkaKorekcija::setFocusLine()
{
	if (requestfromKomintent == 1)
	{
		ui.lineEdit_8->setFocus();
		ui.lineEdit_8->selectAll();
	}
	if (requestfromKomintent == 2)
	{
		ui.lineEdit_2->setFocus();
		ui.lineEdit_2->selectAll();
	}
}
void QProdSmetkaKorekcija::setKomintent(QString text, QString textName)
{
    if(requestfromKomintent == 1)
	{
		ui.lineEdit->setText(textName);
		komintentID = text;
	}
	else
	{
		ui.lineEdit_8->setText(textName);
		prodavnicaID = text;
	}
}

void QProdSmetkaKorekcija::setArtikli(QString text, QString textName)
{
    ui.lineEdit_2->setText(textName);
    textId = text;
    artikal_sifra = text;

	QSqlQuery query;
	query.prepare("select edm, ddv from artikli where id = :id");
	query.bindValue(":id", artikal_sifra);	
	query.exec();
	query.next();
	ui.lineEdit_9->setText(query.value(0).toString());
	ui.lineEdit_10->setText(query.value(1).toString());
}
void QProdSmetkaKorekcija::setSaldo(QString text)
{
}

void QProdSmetkaKorekcija::setFocusLine2()
{
    ui.lineEdit_2->setFocus();
}

void QProdSmetkaKorekcija::on_pushButton2AAA_2_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit_2->text());
    }
    else
    {
        ui.lineEdit_3->setFocus();
    }
}

void QProdSmetkaKorekcija::on_pushButton_3_clicked()
{
	CHelperClass hclass(this);
	if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за артикал е невалиден\nОдбери артикал од листата на артикли!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_2->setFocus();
		return;
	}


	QLocale loc;
	if(textId.toInt() == -1)
	{
		return;
	}

	//m_id = textId.toInt();

	QString temp = "select id, sifra, artikal, edm, ddv from artikli where id =";
	temp += textId;
	QSqlQuery query(temp);
	QString country1 = "";
	QString country2 = "";
	QString country3 = "";
	QString country4 = "";
	QString country5 = "";

	while (query.next()) {
		country1 = query.value(query.record().indexOf("id")).toString();
		country2 = query.value(query.record().indexOf("sifra")).toString();
		country3 = query.value(query.record().indexOf("artikal")).toString();
		country4 = query.value(query.record().indexOf("edm")).toString();
		country5 = query.value(query.record().indexOf("ddv")).toString();
		//        ui.lineEdit->setText(country1);
	}

	int row = model->rowCount();

	//Artikal Id
	QStandardItem *item = new QStandardItem(country1);
	item->setEditable(false);
	item->setTextAlignment(Qt::AlignRight);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(0, 50);
	model->setItem(row, 0, item);

	//Artikal
	item = new QStandardItem(country3);
	item->setTextAlignment(Qt::AlignLeft);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(1, 200);
	model->setItem(row, 1, item);

	//Edm
	item = new QStandardItem(country4);
	item->setTextAlignment(Qt::AlignLeft);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 50);
	model->setItem(row, 2, item);

	// kolicina
	item = new QStandardItem(ui.lineEdit_3->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 100);
	model->setItem(row, 3, item);
	// cena
	item = new QStandardItem(ui.lineEdit_4->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 100);
	model->setItem(row, 4, item);
	// stapka ddv
	item = new QStandardItem(ui.lineEdit_10->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 100);
	model->setItem(row, 5, item);
	// rabat
	item = new QStandardItem(ui.lineEdit_11->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 100);
	model->setItem(row, 6, item);
	// prodazna cena
	item = new QStandardItem(ui.lineEdit_5->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 100);
	model->setItem(row, 7, item);
	// prodazen iznos
	item = new QStandardItem(ui.lineEdit_12->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 100);
	model->setItem(row, 8, item);
	// vk ddv vo prodazna cena
	item = new QStandardItem(ui.lineEdit_13->text());
	item->setTextAlignment(Qt::AlignRight);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 100);
	model->setItem(row, 9, item);

	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();

	ui.lineEdit_2->setStyleSheet(QString( "background-color: none"));
	ui.lineEdit_2->setText("");
	ui.lineEdit_3->setText("");
	ui.lineEdit_4->setText("");
	ui.lineEdit_5->setText("");
	ui.lineEdit_9->setText("");
	ui.lineEdit_10->setText("");
	ui.lineEdit_11->setText("");
	ui.lineEdit_12->setText("");
	ui.lineEdit_13->setText("");

	ui.lineEdit_2->setFocus();

	textId = "-1";
	//	calculate();
}
void QProdSmetkaKorekcija::selectionChanged(QModelIndex modelX,QModelIndex modelY)
{
    selRow = modelX.row();
    editorOpen = false;
    emit closeCell();
}

void QProdSmetkaKorekcija::on_pushButton_6_clicked()
{
    model->removeRow(selRow);
	calculate();
}
void QProdSmetkaKorekcija::pressReturn()
{
    if (ui.pushButton_3->hasFocus())
    {
        on_pushButton_3_clicked();
    }
    else if (ui.pushButton_6->hasFocus())
    {
        on_pushButton_6_clicked();
    }
    else if (ui.tableView->hasFocus())
    {
        if (editorOpen)
        {
            emit closeCell();
        }
        else
        {
            emit editCell();
        }
        editorOpen = !editorOpen;
    }
}
void QProdSmetkaKorekcija::init(int id)
{
    QLocale loc;
    if(id == -1)
    {
        return;
    }
    m_id = id;
    ui.lineEdit_14->setText(QString::number(id, 10));
    QString temp1 = 
        "select dokumenti_prodavnica.id, komintenti.id , komintenti.naziv, dokumenti_prodavnica.datum, dokumenti_prodavnica.datum_plakanje, dokumenti_prodavnica.dok_id_prodavnica  "
        "from dokumenti_prodavnica "
        "left join komintenti on dokumenti_prodavnica.komintent_id = komintenti.id "
        "where dokumenti_prodavnica.dok_tip = 40 and dokumenti_prodavnica.dok_id = ";        
    temp1 += QString::number(id, 10);
    QSqlQuery query1(temp1);
    while (query1.next())
    {
        ui.lineEdit->setText(query1.value(2).toString().isEmpty() ? "" : query1.value(2).toString());
        komintentID = query1.value(1).toString();
        dokumentID = query1.value(0).toString();
        QString a = query1.value(0).toString();
        ui.dateTimeEdit->setDate(query1.value(3).toDate());
		ui.dateTimeEdit_2->setDate(query1.value(4).toDate());
		ui.lineEdit_15->setText(query1.value(5).toString());

	}

	QString temp2 = 
		" SELECT dokumenti_prodavnica.id, komintenti.id , komintenti.naziv, komintenti.adresa, komintenti.grad, komintenti.edb,komintenti.zirosmetka "
		" from dokumenti_prodavnica "
		" LEFT JOIN komintenti ON dokumenti_prodavnica.prodavnica_id = komintenti.id  "
		"where dokumenti_prodavnica.dok_tip = 40 and dokumenti_prodavnica.dok_id = ";        
	temp2 += QString::number(id, 10);
	QSqlQuery query2(temp2);
	while (query2.next())
	{
		prodavnicaID = query2.value(1).toString();
		prodavnicaNaziv = query2.value(2).toString();
		prodavnicaAdresa = query2.value(3).toString();
		prodavnicaGrad = query2.value(4).toString();
		prodavnicaEdb = query2.value(5).toString();
		prodavnicaZiro = query2.value(6).toString();
		ui.lineEdit_8->setText(prodavnicaNaziv);
	}

    int r = 0;
    int c = 10;
    int fieldNo[10];
    QString country[10];
    int colWidth[] = {40, 220, 80, 60, 100, 100, 100, 100, 100, 100, 100};
    QString temp = 
		"select "
		"artikli.id, "
		"artikal, "
		"edm, "
		"kol, "
		"edinecna_prodazna_cena / (1 - rabat / 100) , " // add
		"stapka_ddv, "
		"rabat, "
		"edinecna_prodazna_cena, " 
		"iznos_prodazna, " 
		"vk_ddv_prodazna " 
		"from magacin_prodavnica "
		"left join artikli on magacin_prodavnica.artikal_id = artikli.id "
		"where magacin_prodavnica.dok_tip = 40 and magacin_prodavnica.dok_id=       ";
    temp += QString::number(id, 10);
    QSqlQuery query(temp);
    model = new QStandardItemModel(r,c);
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("Шифра."));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("Назив на\nСтоките"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("Единечна\nмера"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Кол*"));
	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Един.Цена"));
	model->setHeaderData( 5, Qt::Horizontal, trUtf8("Пропишана\nстапка ДДВ"));
	model->setHeaderData( 6, Qt::Horizontal, trUtf8("Рабат"));
	model->setHeaderData( 7, Qt::Horizontal, trUtf8("Цена продажна"));
	model->setHeaderData( 8, Qt::Horizontal, trUtf8("Износ"));
	model->setHeaderData( 9, Qt::Horizontal, trUtf8("ДДВ\nво прод. вредн"));
    ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
    ui.tableView->setHorizontalHeader(header);
    header->show();
    int row = 0;
    while (query.next()) 
    {
        for (int i = 0; i < c; i++)
        {
            QStandardItem *item = NULL;
            QString temp = query.value(i).toString();
            if (i > 2)
            {
                temp = loc.toString(temp.toFloat(), 'f', 2);
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignRight);
            }
            else
            {
                item = new QStandardItem(temp);
                item->setTextAlignment(Qt::AlignLeft);
            }
            item->setEditable(false);
            ui.tableView->setRowHeight(row, 18);
            ui.tableView->setColumnWidth(i, colWidth[i]);
            model->setItem(row, i, item);
        }
        row++;
    } 
    QItemSelectionModel *sm = ui.tableView->selectionModel();
    connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
        this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
    ui.tableView->show();
    ui.lineEdit->setFocus();
	calculate();
}

void QProdSmetkaKorekcija::on_pushButton_5_clicked()
{
    pressEscape();
}

void QProdSmetkaKorekcija::on_pushButton_4_clicked()
{
	QLocale loc;
	if (!validateKomintent())
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за коминтент е невалиден\nОдбери коминтент од листата на коминтенти!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit->setFocus();
		return;
	}
	
	int mmid = loc.toInt(ui.lineEdit_14->text()); 
    int cols = model->columnCount();
    int rows = model->rowCount();
    if (!rows)
    {
        return;
    }


	QSqlDatabase db = QSqlDatabase::database();
	db.transaction();	

	bool sqlStat = true;
	
	QSqlQuery query1;
    query1.clear();
    query1.prepare("update dokumenti_prodavnica set dok_id = :a0, datum=:a1, faktura_id=:a2, mag_id=:a3, komintent_id=:a4, datum_plakanje=:a5 , prodavnica_id=:a6, dok_id_prodavnica = :a7 where dok_id=:aid and dok_tip = 40");
    query1.bindValue(":a0", mmid);	
    query1.bindValue(":a1", ui.dateTimeEdit->dateTime());	
    query1.bindValue(":a2", 0);	
    query1.bindValue(":a3", 0);	
    query1.bindValue(":a4", komintentID);
	query1.bindValue(":a5", ui.dateTimeEdit_2->dateTime());	
	query1.bindValue(":a6", prodavnicaID);
	query1.bindValue(":a7", ui.lineEdit_15->text());
	query1.bindValue(":aid", m_id);	
    
	sqlStat = sqlStat && query1.exec();
    QSqlError err = query1.lastError();

    query1.clear();
    query1.prepare(
        "delete from magacin_prodavnica where dok_tip = 40 and dok_id = :a"
        );
    query1.bindValue(":a", m_id);	
	sqlStat = sqlStat && query1.exec();
    
    QSqlQuery query;
	for (int i = 0; i < rows; i++)
	{

		QString mTipDok = "I";
		QString mEmpty ="Empty";
		QString mArtikalID = model->item(i, 0)->text();
		QString mArtikalArtikal = model->item(i, 1)->text();
		QString mArtikalEdm = model->item(i, 2)->text();
		QString mKol = model->item(i, 3)->text();
		QString mEdinecna_prodazna_cena = model->item(i, 4)->text();
		QString mStapka_ddv = model->item(i, 5)->text();
		QString mRabat = model->item(i, 6)->text();
		QString mCena_prodazna = model->item(i, 7)->text();
		QString mIznos_prodazna = model->item(i, 8)->text();
		QString mVk_ddv_prodazna = model->item(i, 9)->text();

		query.clear();
		query.prepare(
			"insert into magacin_prodavnica(dok_id, dok_tip, artikal_id, kol, stapka_ddv, "
			"edinecna_prodazna_cena, iznos_prodazna, vk_ddv_prodazna, rabat) "
			"values(:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8,:a9)"
			);
		query.bindValue(":a1", m_id);	
		query.bindValue(":a2", 40);	
		query.bindValue(":a3", mArtikalID);	
		query.bindValue(":a4", loc.toFloat(mKol));	
		query.bindValue(":a5", loc.toFloat(mStapka_ddv));	
		query.bindValue(":a6", loc.toFloat(mEdinecna_prodazna_cena));	
		query.bindValue(":a7", loc.toFloat(mIznos_prodazna));	
		query.bindValue(":a8", loc.toFloat(mVk_ddv_prodazna));	
		query.bindValue(":a9", loc.toFloat(mRabat));	

		sqlStat = sqlStat && query.exec();
		QSqlError err = query.lastError();
	}


	if (sqlStat)
	{
		db.commit();
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Сметката е успешно корегиранa"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		pressEscape();
	} 
	else
	{
		db.rollback();
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Сметката НЕ Е корегиранa !!!."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
	}
}
bool QProdSmetkaKorekcija::existDok(int idDok)
{
    int nCount = 0;
    QString temp = "select count(dok_id) br from dokumenti_finansii where dok_tip = 40 and dok_id =";
    temp += QString::number(idDok, 10);
    QSqlQuery query(temp);
    QString country1 = "";
    int fieldNo = query.record().indexOf("br");
    while (query.next()) {
        nCount = query.value(0).toInt() + 1;
    }
    return nCount > 0 ? true : false;
}

bool QProdSmetkaKorekcija::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::FocusIn)
    {
        if (object == ui.lineEdit)
        {
            ui.lineEdit->setStyleSheet("background-color: yellow");
        }
        if (object == ui.lineEdit_2)
        {
            ui.lineEdit_2->setStyleSheet("background-color: yellow");
        }
        if (object == ui.lineEdit_3)
        {
            ui.lineEdit_3->setStyleSheet("background-color: yellow");
        }
        if (object == ui.lineEdit_4)
        {
            ui.lineEdit_4->setStyleSheet("background-color: yellow");
        }
        if (object == ui.lineEdit_5)
        {
            ui.lineEdit_5->setStyleSheet("background-color: yellow");
        }
		if (object == ui.lineEdit_7)
		{
			ui.lineEdit_7->setStyleSheet("background-color: yellow");
		}

		if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: yellow");
        }

    }
    if (event->type() == QEvent::FocusOut)
    {
        if (object == ui.lineEdit)
        {
            ui.lineEdit->setStyleSheet("background-color: none");
        }
        if (object == ui.lineEdit_2)
        {
            ui.lineEdit_2->setStyleSheet("background-color: none");
        }
        if (object == ui.lineEdit_3)
        {
            ui.lineEdit_3->setStyleSheet("background-color: none");
        }
        if (object == ui.lineEdit_4)
        {
            ui.lineEdit_4->setStyleSheet("background-color: none");
        }
        if (object == ui.lineEdit_5)
        {
            ui.lineEdit_5->setStyleSheet("background-color: none");
        }
		if (object == ui.lineEdit_7)
		{
			ui.lineEdit_7->setStyleSheet("background-color: none");
		}
		if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: none");
        }
    }

    return false;
}

void QProdSmetkaKorekcija::on_plineEdit3_Pressed()
{
	ui.lineEdit_4->setFocus();
}

void QProdSmetkaKorekcija::on_plineEdit12_Pressed()
{
	if (ui.lineEdit_12->text().isEmpty())
	{

		QMessageBox msgBox;
		msgBox.setText(trUtf8("Внеси Износ."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_12->setFocus();
	}
	else
	{
		ui.pushButton_3->setFocus();
	}

}

void QProdSmetkaKorekcija::on_plineEdit4_Pressed()
{
	if (ui.lineEdit_5->text().isEmpty())
	{

		QMessageBox msgBox;
		msgBox.setText(trUtf8("Внеси Износ."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_5->setFocus();
	}
	else
	{
		ui.lineEdit_12->setFocus();
	}
}

void QProdSmetkaKorekcija::on_plineEdit7_Pressed()
{
	on_pushButton_3_clicked();
}

void QProdSmetkaKorekcija::openEditor()
{
    //	tableView->closePersistentEditor(indexPrev);
    QModelIndex index;
    QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
    index = indexes.at(0);	// To get the row/column numbers use 
	if ((index.column() == 3)||(index.column() == 5)||(index.column() == 9))
    {
        ui.tableView->openPersistentEditor(index);
    }
    indexPrev = index;
}

void QProdSmetkaKorekcija::closeEditor()
{
	ui.tableView->closePersistentEditor(indexPrev);

	QStandardItem *tempKol = model->item(indexPrev.row(), 3); // kol
	QStandardItem *tempIznosNab = model->item(indexPrev.row(), 5); // iznosNabavna
	QStandardItem *tempDDV = model->item(indexPrev.row(), 7); // ddv
	QStandardItem *tempIznosProd = model->item(indexPrev.row(), 9); // ddv


	if(tempKol)
	{

		QStandardItem *temp = NULL;
		QString valueIznosNab = tempIznosNab->text(); //5
		QString valueDDV = tempDDV->text();//7
		QString valueIznosProd = tempIznosProd->text(); //9

		QLocale loc;
		float edinecnaNabCena = 0;
		float presmetanNablDDV = 0; 
		float edinecnaProdCena = 0; 
		float presmetanProdDDV = 0; 

		if(indexPrev.column() == 3)
		{
			QString valueKol = tempKol->text();  //3 fixed
			QString valueIznosNab = tempIznosNab->text(); //5
			QString valueDDV = tempDDV->text();//7
			QString valueIznosProd = tempIznosProd->text(); //9

			edinecnaNabCena = (loc.toFloat(valueIznosNab) / (loc.toFloat(valueKol))); 
			presmetanNablDDV = (loc.toFloat(valueIznosNab) * (loc.toFloat(valueDDV) / 100)); 
			edinecnaProdCena = (loc.toFloat(valueIznosProd) / (loc.toFloat(valueKol))); 

			temp = model->item(indexPrev.row(), 3);
			temp->setText(loc.toString(loc.toFloat(valueKol) , 'f', 2));
			temp = model->item(indexPrev.row(), 4);
			temp->setText(loc.toString(edinecnaNabCena , 'f', 2));
			temp = model->item(indexPrev.row(), 6);
			temp->setText(loc.toString(presmetanNablDDV , 'f', 2));
			temp = model->item(indexPrev.row(), 8);
			temp->setText(loc.toString(edinecnaProdCena , 'f', 2));
		}
		if(indexPrev.column() == 5)
		{
			QString valueKol = tempKol->text();  //3 
			QString valueIznosNab = tempIznosNab->text(); //5 fixed
			QString valueDDV = tempDDV->text();//7
			QString valueIznosProd = tempIznosProd->text(); //9

			edinecnaNabCena  = (loc.toFloat(valueIznosNab) / (loc.toFloat(valueKol))); 
			presmetanNablDDV = (loc.toFloat(valueIznosNab) * (loc.toFloat(valueDDV) / 100)); 

			temp = model->item(indexPrev.row(), 5);
			temp->setText(loc.toString(loc.toFloat(valueIznosNab) , 'f', 2));
			temp = model->item(indexPrev.row(), 4);
			temp->setText(loc.toString(edinecnaNabCena , 'f', 2));
			temp = model->item(indexPrev.row(), 6);
			temp->setText(loc.toString(presmetanNablDDV , 'f', 2));

		}
		if(indexPrev.column() == 9)
		{
			QString valueKol = tempKol->text();  //3 
			QString valueIznosNab = tempIznosNab->text(); //5 
			QString valueDDV = tempDDV->text();//7
			QString valueIznosProd = tempIznosProd->text(); //9 fixed

			edinecnaProdCena = loc.toFloat(valueIznosProd) / loc.toFloat(valueKol); 
			presmetanProdDDV = (loc.toFloat(valueIznosProd) / (1 + (loc.toFloat(valueDDV) / 100))) * (loc.toFloat(valueDDV) / 100); 

			temp = model->item(indexPrev.row(), 9);
			temp->setText(loc.toString(loc.toFloat(valueIznosProd) , 'f', 2));
			temp = model->item(indexPrev.row(), 8);
			temp->setText(loc.toString(edinecnaProdCena , 'f', 2));
			temp = model->item(indexPrev.row(), 10);
			temp->setText(loc.toString(presmetanProdDDV , 'f', 2));
		}

	}
	updateModelData();

}

bool QProdSmetkaKorekcija::validateKomintent()
{
	bool stat = false;
	CHelperClass hclass(this);
	if (hclass.isKomintentExists(ui.lineEdit->text()))
	{
		stat = true;
	}
	return stat;
}

void QProdSmetkaKorekcija::callImportIspratnici()
{
	emit scallIspratnici((QWidget*)this, "");
}

void QProdSmetkaKorekcija::callImportProfaktura()
{
	emit scallProfakturi((QWidget*)this, "");
}


void QProdSmetkaKorekcija::setProfakturaID(QString text)
{
	QLocale loc;
	int r = 0;
	int c = 8;
	int fieldNo[8];
	QString country[8];
	int colWidth[] = {40, 70, 220, 60, 100, 100, 100, 100};
	QString colName[] = {"id", "sifra", "artikal", "edm", "ddv", "ikol", "icena", "rabat" };
	QString temp = 
		"select artikli.id, sifra, artikal, edm, artikli.ddv, ikol, icena, rabat "
		"from finansovi_stavki "
		"left join artikli on finansovi_stavki.artikal_id=artikli.id "
		"where finansovi_stavki.dok_tip = 60 and finansovi_stavki.dok_id= ";
	temp += text;
	QSqlQuery query(temp);
	ui.tableView->setModel(model);
	header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
	header->show();
	//int row = 0;
	while (query.next()) 
	{
		int row = model->rowCount();
		for (int i = 0; i < c; i++)
		{
			fieldNo[i] = query.record().indexOf(colName[i]);
			QStandardItem *item = NULL;
			QString temp = query.value(fieldNo[i]).toString();
			if (i > 3)
			{
				temp = loc.toString(temp.toFloat(), 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else
			{
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignLeft);
			}
			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
		}
		row++;
	} 
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
	ui.lineEdit->setFocus();
	calculate();
}

void QProdSmetkaKorekcija::setIspratnicaID(QString text)
{
	QLocale loc;

	int r = 0;
	int c = 11;
	int fieldNo[11];
	QString country[8];
	int colWidth[] = {40, 220, 80, 80, 100, 100, 100, 100, 100, 100, 100};
	QString temp = 
		"select artikli.id, artikal, edm, ikol, 0, 0, 0, artikli.ddv, 0, 0, 0  "
		"from magacin "
		"left join artikli on magacin.artikal_id=artikli.id "
		"where (magacin.dok_tip = 40 or magacin.dok_tip = 44) and magacin.dok_id= ";
	temp += text;
	QSqlQuery query(temp);

	ui.tableView->setModel(model);
	header = new QHeaderView(Qt::Horizontal, this);
	header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
	header->show();
	//int row = 0;
	while (query.next()) 
	{
		int row = model->rowCount();
		for (int i = 0; i < c; i++)
		{
			QStandardItem *item = NULL;
			QString temp = "";
			temp = query.value(i).toString();

			if ((i > 2))
			{
				temp =  loc.toString(temp.toFloat(), 'f', 2);
				item = new QStandardItem(temp);
				item->setTextAlignment(Qt::AlignRight);
			}
			else
			{
				item = new QStandardItem(temp);
				if (i == 6)
				{
					item->setTextAlignment(Qt::AlignRight);
				}
				else
				{
					item->setTextAlignment(Qt::AlignLeft);
				}
			}

			item->setEditable(false);
			ui.tableView->setRowHeight(row, 18);
			ui.tableView->setColumnWidth(i, colWidth[i]);
			model->setItem(row, i, item);
		}        
		row++;
	} 
	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();
	ui.lineEdit->setFocus();
	calculate();
}

void QProdSmetkaKorekcija::calculate()
{
	QLocale loc;
	float VKsuma = 0;
	float Iznos = 0;
	float ddv = 0;
	float kol = 0;
	float cena = 0;
	float rabat = 0;
	for (int i = 0;  i < model->rowCount(); i++)
	{
		ddv = loc.toFloat(model->item( i, 4)->text());
		kol = loc.toFloat(model->item( i, 5)->text());
		cena = loc.toFloat(model->item( i, 6)->text());
		rabat = loc.toFloat(model->item( i, 7)->text());
		Iznos = kol * cena * (1 - rabat/100);
		VKsuma += Iznos;
	}
//	ui.lineEdit_8->setText(loc.toString( VKsuma, 'f', 2));
}


void QProdSmetkaKorekcija::updateModelData()
{
	QLocale loc;
	float kol = ui.lineEdit_3->text().toFloat();
	float cena = ui.lineEdit_4->text().toFloat();
	float rabat = ui.lineEdit_11->text().toFloat();
	float ddvProcent = ui.lineEdit_10->text().toFloat();

	float prodaznaCena = cena * (1 - rabat / 100);
	float prodaznaIznos = kol * prodaznaCena;
	float presmetanIzlDDV = (prodaznaIznos / (1 + ddvProcent / 100)) * (ddvProcent / 100); 

	ui.lineEdit_5->setText(loc.toString( prodaznaCena , 'f', 2));
	ui.lineEdit_12->setText(loc.toString( prodaznaIznos , 'f', 2));
	ui.lineEdit_13->setText(loc.toString( presmetanIzlDDV , 'f', 2));
}

